package com.main.prioritysms;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TextSender extends Activity{
	
	/*TODO onstart method to be called when either compose or reply is selected.
	 * This will mean that instances of the textsender class will be created
	 * and build from separate xml (reply) files
	 */
	
	//Debug
	private static final String TAG = "SMS app";
	private static final boolean D = true;
	
	//Layout views
	private Button btnSendSMS;
	private ListView mConversationView;
	
	//Array adapter
	private ArrayAdapter<String> mConversationArrayAdapter;
	
	//String buffer for outgoing messages
	private StringBuffer mOutStringBuffer;
	
	//Bundle to pass message back to the database
	public Bundle messageToStore;
	
	//Message strings
	private String message;
	private String receivedMessage;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	if(D) Log.e(TAG, "+++ON CREATE+++");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reply);
    	setUpMessages();
    }
    
    @Override
    public void onStart(){
    	super.onStart();
    	if(D) Log.e(TAG, "+++ON START+++");
    }
	
    public void setUpMessages(){
    	Log.d(TAG, "setUpMessages()");
    	
        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.sentMessages);
        mConversationView.setAdapter(mConversationArrayAdapter);
        
        //Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
        
        //Initialize the send button with the onClick listener
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        btnSendSMS.setOnClickListener(new OnClickListener() {
        	public void onClick(View v){
        		TextView messageBox = (TextView) findViewById(R.id.txtMessage);
        		TextView phoneNumBox = (TextView) findViewById(R.id.txtPhoneNo);
        		message = messageBox.getText().toString();
        		String number = phoneNumBox.getText().toString();
        		
        		if(number.length() > 0 && message.length() > 0){
        			sendSMS(number, message);
        			
        			//mConversationArrayAdapter.add("Me: " + message);
        			
                    //Reset the out string buffer
                    mOutStringBuffer.setLength(0);
                    messageBox.setText(mOutStringBuffer);
        		}
        		else{
        			Toast.makeText(getBaseContext(), "Please enter both phone number and message.", Toast.LENGTH_SHORT).show();
        		}
        	}
        });
        

    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	finish();
    }
    
    
	 public void sendSMS(String phoneNumber, String message){
	    	//PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMSTest.class), 0);
	    	//SmsManager sms = SmsManager.getDefault();
	    	//sms.sendTextMessage(phoneNumber, null, message, pi, null);
	        String SENT = "SMS_SENT";
	        String DELIVERED = "SMS_DELIVERED";
	 
	        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
	            new Intent(SENT), 0);
	 
	        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
	            new Intent(DELIVERED), 0);
	 
	        //---when the SMS has been sent---
		        registerReceiver(new BroadcastReceiver(){
		            @Override
		            public void onReceive(Context arg0, Intent arg1) {
		                switch (getResultCode())
		                {
		                    case Activity.RESULT_OK:
		                        Toast.makeText(getBaseContext(), "SMS sent", 
		                                Toast.LENGTH_SHORT).show();
		                        populateMessages(1);
		                        break;
		                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
		                        Toast.makeText(getBaseContext(), "Generic failure", 
		                                Toast.LENGTH_SHORT).show();
		                        break;
		                    case SmsManager.RESULT_ERROR_NO_SERVICE:
		                        Toast.makeText(getBaseContext(), "No service", 
		                                Toast.LENGTH_SHORT).show();
		                        break;
		                    case SmsManager.RESULT_ERROR_NULL_PDU:
		                        Toast.makeText(getBaseContext(), "Null PDU", 
		                                Toast.LENGTH_SHORT).show();
		                        break;
		                    case SmsManager.RESULT_ERROR_RADIO_OFF:
		                        Toast.makeText(getBaseContext(), "Radio off", 
		                                Toast.LENGTH_SHORT).show();
		                        break;
		                }
		            }
		    }, new IntentFilter(SENT));
		        
	        registerReceiver(new BroadcastReceiver(){
	            @Override
	            public void onReceive(Context arg0, Intent arg1) {
	                switch (getResultCode())
	                {
	                    case Activity.RESULT_OK:
	                        Toast.makeText(getBaseContext(), "SMS delivered", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                    case Activity.RESULT_CANCELED:
	                        Toast.makeText(getBaseContext(), "SMS not delivered", 
	                                Toast.LENGTH_SHORT).show();
	                        break;                        
	                }
	            }
	        }, new IntentFilter(DELIVERED));
	        SmsManager sms = SmsManager.getDefault();
	        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	    }
	 
	    public void setReceivedMessage(String str){
	    	receivedMessage = str;
	    }
	    
	    public void populateMessages(int i){
	    	if(i == 1){
	    		mConversationArrayAdapter.add("Me: " + message);
	    		messageToStore.putString("Me", "Me: " + message);
	    	}
	    	else{
	    		/*TODO: 
	    		 * Develop the functionality to handle the user receiving messages
	    		 */
	    		mConversationArrayAdapter.add(receivedMessage);
	    		messageToStore.putString("NotMe", "NotMe: " + message);
	    	}
	    }
}
